package com.yumeng.framework.core.mvc.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

import static org.springframework.http.HttpHeaders.*;

/**
 * 跨域Filter
 *
 * @author wxd
 * @date 2024/6/7 下午3:21
 */
public class CorsFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, httpRequest.getHeader("origin"));
        httpResponse.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        httpResponse.setHeader(ACCESS_CONTROL_ALLOW_METHODS, "POST, PUT, GET, OPTIONS, DELETE");
        httpResponse.setHeader(ACCESS_CONTROL_MAX_AGE, "3600");
        httpResponse.setHeader(ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type, X-Token");

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
